package com.esun.rabbit2.viewer.mainact.lotteryhallact;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Random;

import android.app.ActivityGroup;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.UserInfo;
import com.esun.model.sportteryfootballshengfu.SportteryFootballShengfuLotteryInfo;
import com.esun.rabbit2.viewer.LoginAct;
import com.esun.rabbit2.viewer.mainact.hemaicenteragp.ShengfucaiHemaiListAct;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.sportteryfootballshengfu.SportteryFootballShengfuChooseAct;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.sportteryfootballshengfu.SportteryFootballShengfuChooseList;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.LotteryInfoListAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord.FootballShengfuListAct;
import com.esun.ui.R;
import com.esun.util.Vibrate;
import com.esun.util.log.EDebug;

/**
 * @ClassName: SportteryFootballShengfuAgp
 * @Description: 足 彩 胜 负
 * @author: Liujun liuj@500wan.com
 * @date: 2012-4-12 下午4:51:55
 * 
 */
@SuppressWarnings("deprecation")
public class SportteryFootballShengfuAgp extends ActivityGroup implements OnClickListener, OnTabChangeListener, SensorListener {

	/** 投注选队页面编号 */
	private static final String TAB_CHOOSE = "0";

	/** 参与和买页面编号 */
	private static final String TAB_HEMAI = "1";

	/** 购彩记录页面编号 */
	private static final String TAB_LOTTERY_RECORD = "2";

	/** 开奖信息页面编号 */
	private static final String TAB_LOTTER_INFO = "3";

	/** 玩法介绍页面编号 */
	private static final String TAB_INTRODACTION = "4";

	/** 选队 */
	public static final int IN_CHOOSE_VIEW = 10001;

	/** 投注 */
	public static final int IN_LIST_VIEW = 10002;



	private TabHost sportteryFootballShengfuTabHostMain;
	private ImageButton btnSportteryFootballShengfuAgpCancel; // 返回
	private ImageButton btnSportteryFootballShengfuAgpMenu; // 菜单

	private boolean isSensor = false;
	private ArrayList<Hashtable<String, Object>> storecheckvalues;

	private Dialog menuDialog = null;
	/** Button */
	private Button menuBtnChoose; // 投号选注
	private Button menuBtnHemai; // 参与和买
	private Button menuBtnLotteryRecord; // 购彩记录
	private Button menuBtnLotteryInfo; // 开奖信息
	private Button menuBtnIntroduction; // 玩法介绍

	private LinearLayout linearMenuBg;

	/** Textview */
	private TextView tvTitle; // 界面标题

	private int CURRENT_TAB_NUM; // 当前tab编号
	private Bundle bundleSetCurrentTab;

	public static Handler handlerSportteryFootballShengfuAgp;

	/************************* 晃动相关 **********************/
	private SensorManager sensorMgr;
	private long lastUpdate = -1;
	private float x, y, z;
	private float last_x, last_y, last_z;
	private static final int SHAKE_THRESHOLD = 800;

	/*******************************************************/

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sportteryfootballshengfu_agp);
		bundleSetCurrentTab = this.getIntent().getExtras();
		CURRENT_TAB_NUM = bundleSetCurrentTab.getInt("CURRENT_TAB_NUM");

		handlerInit();
		uiInIt();

	}

	/** handler处理 */
	private void handlerInit() {
		handlerSportteryFootballShengfuAgp = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case IN_CHOOSE_VIEW:
					tvTitle.setText(Language.MSG_SHENGFUCAI_XUANDUI);
					isSensor = true;
					break;

				case IN_LIST_VIEW:
					tvTitle.setText(Language.MSG_SHENGFUCAI_TOUZHU);
					isSensor = false;
					break;

				default:
					break;
				}
			}
		};
	}

	/** 界面初始化 */
	private void uiInIt() {

		tabInit();
		tvTitle = (TextView) findViewById(R.id.sportteryfootballshengfuagp_tv_title);
		tvTitle.setText("足彩胜负投注");
		btnSportteryFootballShengfuAgpCancel = (ImageButton) findViewById(R.id.sportteryfootballshengfuagp_btn_cancel);
		btnSportteryFootballShengfuAgpCancel.setOnClickListener(this);
		btnSportteryFootballShengfuAgpMenu = (ImageButton) findViewById(R.id.sportteryfootballshengfuagp_btn_menu);
		btnSportteryFootballShengfuAgpMenu.setOnClickListener(this);
		if (CURRENT_TAB_NUM == 0) {
			tvTitle.setText(Language.MSG_SHENGFUCAI_XUANDUI);
			isSensor = true;
		} else if (CURRENT_TAB_NUM == 1) {
			tvTitle.setText(Language.MSG_SHENGFUCAI_HEMAI);
			isSensor = false;
		}

	}

	/** tab 内容初始化 */
	private void tabInit() {
		sportteryFootballShengfuTabHostMain = (TabHost) findViewById(R.id.sportteryfootballshengfuagp_tabhost_main);
		sportteryFootballShengfuTabHostMain.setup(SportteryFootballShengfuAgp.this.getLocalActivityManager());
		// 投号选注
		TabSpec ts0 = sportteryFootballShengfuTabHostMain.newTabSpec(TAB_CHOOSE);
		ts0.setIndicator("");
		ts0.setContent(new Intent(this, SportteryFootballShengfuChooseAct.class));
		sportteryFootballShengfuTabHostMain.addTab(ts0);
		// 参与和买
		TabSpec ts1 = sportteryFootballShengfuTabHostMain.newTabSpec(TAB_HEMAI);
		ts1.setIndicator("");
		ts1.setContent(new Intent(this, ShengfucaiHemaiListAct.class));
		sportteryFootballShengfuTabHostMain.addTab(ts1);
		// 购彩记录
		TabSpec ts2 = sportteryFootballShengfuTabHostMain.newTabSpec(TAB_LOTTERY_RECORD);
		ts2.setIndicator("");
		ts2.setContent(new Intent(this, FootballShengfuListAct.class));
		sportteryFootballShengfuTabHostMain.addTab(ts2);
		// 开奖信息
		TabSpec ts3 = sportteryFootballShengfuTabHostMain.newTabSpec(TAB_LOTTER_INFO);
		ts3.setIndicator("");
		ts3.setContent(new Intent(this, LotteryInfoListAct.class).putExtra("lotid", Config.SHENGFUCAI));
		sportteryFootballShengfuTabHostMain.addTab(ts3);
		// 玩法介绍
		TabSpec ts4 = sportteryFootballShengfuTabHostMain.newTabSpec(TAB_INTRODACTION);
		ts4.setIndicator("");
		ts4.setContent(new Intent(this, HelpAct.class).putExtra("url", Config.SPORTTERYFOOTBALLSHENGFU_INTRODUCE_WEB_ADD).putExtra("title", Config.NULLMARK).putExtra("havetitle", Config.NUM0));
		sportteryFootballShengfuTabHostMain.addTab(ts4);

		sportteryFootballShengfuTabHostMain.setCurrentTab(CURRENT_TAB_NUM);
		sportteryFootballShengfuTabHostMain.setOnTabChangedListener(this);
	}

	private void setMenuDialog() {
		menuDialog = new Dialog(this, R.style.dialogNoFloating);
		menuDialog.getWindow().setContentView(R.layout.sportteryfootballshengfu_agp_dialog_menu);

		menuBtnChoose = (Button) menuDialog.getWindow().findViewById(R.id.footballshengfuagpdialogmenu_btn_choose);
		menuBtnChoose.setOnClickListener(this);

		menuBtnHemai = (Button) menuDialog.getWindow().findViewById(R.id.footballshengfuagpdialogmenu_btn_hemai);
		menuBtnHemai.setOnClickListener(this);

		menuBtnLotteryRecord = (Button) menuDialog.getWindow().findViewById(R.id.footballshengfuagpdialogmenu_btn_lotteryRecord);
		menuBtnLotteryRecord.setOnClickListener(this);

		menuBtnLotteryInfo = (Button) menuDialog.getWindow().findViewById(R.id.footballshengfuagpdialogmenu_btn_lotteryInfo);
		menuBtnLotteryInfo.setOnClickListener(this);

		menuBtnIntroduction = (Button) menuDialog.getWindow().findViewById(R.id.footballshengfuagpdialogmenu_btn_introduction);
		menuBtnIntroduction.setOnClickListener(this);

		linearMenuBg = (LinearLayout) menuDialog.getWindow().findViewById(R.id.footballshengfuagp_dialog_menu_linear_bg);
		linearMenuBg.setOnClickListener(this);

		menuDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {

			}
		});

		menuDialog.show();

	}

	/** 点击事件监听类 （包括左上角的返回 ， 筛选 ，和右上角的菜单里面的点击事件处理 ） */
	@Override
	public void onClick(View v) {

		Message msgRefresh;
		msgRefresh = handlerSportteryFootballShengfuAgp.obtainMessage(Config.DO_REFRESH, null);

		switch (v.getId()) {

		case R.id.sportteryfootballshengfuagp_btn_cancel:
			SportteryFootballShengfuAgp.this.finish();
			break;

		case R.id.sportteryfootballshengfuagp_btn_menu:
			setMenuDialog();
			break;

		case R.id.footballshengfuagpdialogmenu_btn_choose:
			sportteryFootballShengfuTabHostMain.setCurrentTab(0);
			menuDialog.dismiss();
			break;

		case R.id.footballshengfuagpdialogmenu_btn_hemai:
			sportteryFootballShengfuTabHostMain.setCurrentTab(1);
			menuDialog.dismiss();
			break;

		case R.id.footballshengfuagpdialogmenu_btn_lotteryRecord:
			if (isLogin()) {
				sportteryFootballShengfuTabHostMain.setCurrentTab(2);
				// 暂时去掉 刷新影响流畅性
				FootballShengfuListAct.handlerGetFootballLotteryRecord.sendMessage(msgRefresh);
			} else {
				startActivity(new Intent(SportteryFootballShengfuAgp.this, LoginAct.class));
			}
			menuDialog.dismiss();
			break;

		case R.id.footballshengfuagpdialogmenu_btn_lotteryInfo:
			sportteryFootballShengfuTabHostMain.setCurrentTab(3);
			menuDialog.dismiss();
			break;

		case R.id.footballshengfuagpdialogmenu_btn_introduction:
			sportteryFootballShengfuTabHostMain.setCurrentTab(4);
			menuDialog.dismiss();
			break;

		case R.id.footballshengfuagp_dialog_menu_linear_bg:
			menuDialog.dismiss();
			break;
		default:

			break;
		}
	}

	private boolean isLogin() {
		if (UserInfo.getUserInfo().getUserSession().length() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/** 右上角菜单里面的 通过下面这个类 来获得tabID 通过判断来显示最上面中央字体显示的不同 */
	@Override
	public void onTabChanged(String tabId) {

		int index = Integer.valueOf(tabId);
		switch (index) {
		case 0:
			if (((SportteryChooseActivity) sportteryFootballShengfuTabHostMain.getCurrentView().getContext()).getCurrentPageFlag() == 0) {
				tvTitle.setText(Language.MSG_SHENGFUCAI_XUANDUI);
				isSensor = true;

			} else if (((SportteryChooseActivity) sportteryFootballShengfuTabHostMain.getCurrentView().getContext()).getCurrentPageFlag() == 1) {
				tvTitle.setText(Language.MSG_SHENGFUCAI_TOUZHU);
				isSensor = false;
			}
			break;

		case 1:
			tvTitle.setText(Language.MSG_SHENGFUCAI_HEMAI);
			isSensor = false;
			break;

		case 2:
			tvTitle.setText(Language.MSG_SHENGFUCAI_LOTTERYRECORD);
			isSensor = false;
			break;

		case 3:
			tvTitle.setText(Language.MSG_SHENGFUCAI_LOTTERYINFO);
			isSensor = false;
			break;

		case 4:
			tvTitle.setText(Language.MSG_SHENGFUCAI_INTRODUCTION);
			isSensor = false;
			break;

		default:
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			setMenuDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onTrackballEvent(MotionEvent event) {
		return true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		initShake();
		super.onResume();
	}

	@Override
	protected void onPause() {

		if (sensorMgr != null) {
			sensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
			sensorMgr = null;
		}

		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onAccuracyChanged(int sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	public ArrayList<Integer> randomNum() {

		int howMany = 14;

		Random random = new Random();

		HashSet<Integer> randomArray = new HashSet<Integer>();

		ArrayList<Integer> intList = new ArrayList<Integer>();

		while (true) {
			int temp = random.nextInt(100);
			if (temp != 0) {
				randomArray.add(temp);
			}
			if (randomArray.size() == howMany) {
				break;
			}
		}

		Iterator<Integer> iterator = randomArray.iterator();

		while (iterator.hasNext()) {
			intList.add(iterator.next() % 3);
		}
		for (int i = 0; i < intList.size(); i++) {
			EDebug.o("pring by liuj =============>> random num -------------- = " + Integer.toString(intList.get(i)));
		}
		return intList;
	}

	/** 更新storecheckvalues 用于摇晃 */
	private void updateStorecheckvalues() {
		storecheckvalues.clear();
		EDebug.o(this, "list info size = " + SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getlistInfo().size());
		if (SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getlistInfo().size() > 0) {
			for (int i = 0; i < SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getlistInfo().size(); i++) {
				storecheckvalues.add(tableInListContentNotTitle(i));
			}
		}
	}

	/** 固定的hashtable 存储一些固定的键值对 */
	private Hashtable<String, Object> tableInListContentNotTitle(int position) {
		Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
		hashtable.put(Key.KEY_INFO, SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getlistInfo().get(position));
		hashtable.put(Key.KEY_IS_TITLE, false);
		hashtable.put(Key.KEY_W, false);
		hashtable.put(Key.KEY_D, false);
		hashtable.put(Key.KEY_L, false);
		hashtable.put(Key.KEY_IS_ACTIVE, false);
		return hashtable;
	}

	@Override
	public void onSensorChanged(int sensor, float[] values) {
		if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
			long curTime = System.currentTimeMillis();
			if ((curTime - lastUpdate) > 100) {
				long diffTime = (curTime - lastUpdate);
				lastUpdate = curTime;

				x = values[SensorManager.DATA_X];
				y = values[SensorManager.DATA_Y];
				z = values[SensorManager.DATA_Z];

				float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

				if (speed > SHAKE_THRESHOLD) {
					if (isSensor) {
						new Vibrate(this).playVibrate(-1);
						ArrayList<Integer> intList = new ArrayList<Integer>();
						storecheckvalues = new ArrayList<Hashtable<String, Object>>();
						intList = randomNum();
						updateStorecheckvalues();
						EDebug.o(this, "storecheckvalues size = " + storecheckvalues.size());
						if (storecheckvalues.size() > 0) {
							for (int i = 0; i < storecheckvalues.size(); i++) {
								EDebug.o(this, "i = " + i);
								if (intList.get(i) == 1) {
									storecheckvalues.get(i).put(Key.KEY_W, true);
									storecheckvalues.get(i).put(Key.KEY_IS_ACTIVE, true);
								}
								if (intList.get(i) == 2) {
									storecheckvalues.get(i).put(Key.KEY_D, true);
									storecheckvalues.get(i).put(Key.KEY_IS_ACTIVE, true);
								}
								if (intList.get(i) == 0) {
									storecheckvalues.get(i).put(Key.KEY_L, true);
									storecheckvalues.get(i).put(Key.KEY_IS_ACTIVE, true);
								}
							}

							SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getLotterList().clear();
							SportteryFootballShengfuLotteryInfo.getSportteryFootballShengfuLotteryInfo().getLotterList().addAll(storecheckvalues);
							Message message = SportteryFootballShengfuChooseList.handlerChoosePage.obtainMessage(SportteryFootballShengfuChooseList.RANDOM_CHOOSE_SHENGFUCAI, null);
							SportteryFootballShengfuChooseList.handlerChoosePage.sendMessage(message);
						}
					}
				}
				last_x = x;
				last_y = y;
				last_z = z;
			}
		}

	}

	private void initShake() {
		sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
		boolean accelSupported = sensorMgr.registerListener(this, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME);

		if (!accelSupported) {
			// on accelerometer on this device
			sensorMgr.unregisterListener(this, SensorManager.SENSOR_ACCELEROMETER);
		}
	}
}
